package com.santu.edu.supporter.interceptor;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.core.MethodParameter;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodReturnValueHandler;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Map;

/**
 * @author luoyaoqi
 * @createTime 2024/2/23
 * @description
 */
public class ReturnValueHandler implements HandlerMethodReturnValueHandler {

    private final HandlerMethodReturnValueHandler returnValueHandler;

    public ReturnValueHandler(HandlerMethodReturnValueHandler returnValueHandler) {
        this.returnValueHandler = returnValueHandler;
    }

    @Override
    public boolean supportsReturnType(MethodParameter methodParameter) {
        return returnValueHandler.supportsReturnType(methodParameter);
    }

    @Override
    public void handleReturnValue(Object returnValue, MethodParameter methodParameter, ModelAndViewContainer modelAndViewContainer, NativeWebRequest nativeWebRequest) throws Exception {
        Method method = methodParameter.getMethod();
        if (method != null) {
            RespJson respJson = (RespJson)method.getAnnotation(RespJson.class);
            if (respJson == null || respJson.required()) {
                int code = respJson == null ? 200 : respJson.code();
                ResponseData<Object> responseData = new ResponseData();
                if (returnValue instanceof Page) {
                    Page<?> page = (Page)returnValue;
                    Map<String, Object> dMap = new HashMap(6);
                    dMap.put("list", page.getRecords());
                    dMap.put("pages", page.getPages());
                    dMap.put("total", page.getTotal());
                    responseData.setData(dMap);
                } else {
                    responseData.setData(returnValue);
                }

                responseData.setCode(code);
                responseData.setMsg("成功");
                returnValue = responseData;
            }
        }

        this.returnValueHandler.handleReturnValue(returnValue, methodParameter, modelAndViewContainer, nativeWebRequest);
    }
}
